import asyncio
from lib.sensors import ws2812
from utils.common import integerToRGB
__service__ = "ws2812_http_manager"
__description__ = "manage ws2812 effect"


def init():
    print("ws2812 http manager service started")
    
_ws2812 = None
config = {
    "update_time": 0,
    "light_num": 8,
    "brightness": 100,
    "enable": 1,
    "rgbColor": 16711680,
    "pin": 1
}
response = {
    "update_time": 0
}

async def run():
    global _ws2812,config,response
    while True:
        if response["update_time"] > config["update_time"]:
            #print("update ws2812 config")
            config["update_time"] = response["update_time"]
            if _ws2812:
                _ws2812.clear()
            _ws2812 = ws2812.WS2812(config["pin"], config["light_num"])
            #print(config["pin"],config["light_num"])
        if _ws2812:
             if config["enable"] == 1:
                _ws2812.setBrightness(config["brightness"])
                _ws2812.fill(config["rgbColor"])
             elif config["enable"] == 0:
                _ws2812.clear()
        await asyncio.sleep_ms(5)

async def task():
    from lib.api.ws2812 import get_ws2812_info
    while True:
        resp = get_ws2812_info()
        #print(resp)
        update_time = resp["update_timestamp"]
        response["update_time"] = update_time
        config["light_num"] = resp["light_num"]
        config["brightness"] = resp["brightness"]
        config["enable"] = resp["enable"]
        originalRGB = integerToRGB(resp["rgbColor"])
        # print(originalRGB)
        config["rgbColor"] = originalRGB
        config["pin"] = resp["pin"]
        await asyncio.sleep_ms(1000)